<template>
  <span>
    <template v-if="readonly">
      {{ value_display }}
    </template>

    <template v-else>
      <OInputM2o
        v-model="value2"
        :options="options"
        :placeholder="node.placeholder || node.string"
        @dropdownVisibleChange="dropdownVisibleChange"
        @change="onChange"
        @search="handleSearch"
        @search-more="searchMore"
      />

      <a-form-item-rest>
        <a-modal
          v-model:open="moreOpen"
          title="搜索"
          width="600px"
          @ok="onMoreSubmit"
        >
          <div>选择: {{ moreCurrent.display_name }}</div>
          <a-table
            :dataSource="moreRecords"
            :columns="moreColumns"
            :customRow="moreTableCustomRow"
            style="margin-top: 5px"
          >
          </a-table>
        </a-modal>
      </a-form-item-rest>
    </template>
  </span>
</template>

<script setup>
import api from '@/odoojs/index.js'

import OInputM2o from '../OInput/OInputM2o.vue'

import { computed, ref } from 'vue'
import { useWidget } from './userWidget'

const props = defineProps(['modelValue', 'node', 'formInfo'])
const emit = defineEmits(['update:modelValue', 'change'])

const useData = useWidget(props, { emit })

const { readonly } = useData
const { value2, onChange } = useData

const value_display = computed(() => {
  const fname = props.node.name
  const { record = {} } = props.formInfo || {}
  const val = record[fname] || {}
  return val.display_name
})

const optionsRaw = ref([])

const options = computed(() => {
  const ops = optionsRaw.value

  const val = value2.value || { id: null, display_name: null }

  const me = ops.filter(item => item[0] === val.id)
  const ops2 = me.length
    ? ops
    : [...(val.id ? [[val.id, val.display_name]] : []), ...ops]

  return ops2
})

async function dropdownVisibleChange() {
  // console.log('dropdownVisibleChange')
  const ops = await call_loadSelectOptions()
  // console.log('dropdownVisibleChange ops  ', ops)

  optionsRaw.value = ops
}

async function handleSearch(val) {
  // console.log('handleSearch:', val)
  const ops = await call_loadSelectOptions({ name: val })
  optionsRaw.value = ops
}

async function searchMore() {
  // console.log('searchMore')
  moreLoadData()
  moreOpen.value = true
}

const moreRecords = ref([])
const moreColumns = ref([
  {
    dataIndex: 'display_name',
    key: 'display_name',
    title: '名称'
    // align: 'center'
  }
])

const moreCurrent = ref({})
const moreOpen = ref(false)

async function moreLoadData() {
  const ops = await call_loadSelectOptions({ limit: 0 })

  moreRecords.value = ops.map(item => {
    return { id: item[0], display_name: item[1] }
  })
}

function moreTableCustomRow(record) {
  return {
    // eslint-disable-next-line no-unused-vars
    onClick: event => {
      // console.log('click row ', record)
      moreCurrent.value = record
    }
  }
}

const onMoreSubmit = () => {
  const record = moreCurrent.value
  moreCurrent.value = {}
  onChange(record)
  moreOpen.value = false
}

async function call_loadSelectOptions(kw = {}) {
  const { record = {} } = props.formInfo || {}
  const { meta, domain = [] } = props.node
  const rel = api.env.relation({ ...meta, domain })
  return rel.load_select_options({ record, ...kw })
}
</script>

<style type="text/css"></style>
